<?php

namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\facade\Session;

class Carts extends BaseController
{
    // 用户购物车
    public function index()
    {
        $user = Session::get('user');
        $items = Db::table('carts')->where('uid', $user['id'])->order('id', 'desc')->select();
        $skus = Db::table('product_sku')->whereIn('out_no', $items->column('sku_out_no'))->column('*', 'out_no');
        $data['items'] = $items->map(function ($item) use ($skus) {
            $item['sku_title'] = $skus[$item['sku_out_no']]['sku_title'];
            $item['price'] = $skus[$item['sku_out_no']]['price'];
            $item['money'] = $item['count'] * $item['price'];
            $item['stock'] = $skus[$item['sku_out_no']]['stock'];
            return $item;
        });
        return view('/carts/index', $data);
    }

    // 购物车删除商品
    public function del()
    {
        $user = Session::get('user');
        $id = (int)input('post.id');
        Db::table('carts')->where('uid', $user['id'])->where('id', $id)->delete();
        exit(json_encode(['code' => 0, 'msg' => '删除成功']));
    }

    // 重新计算金额
    public function remoney()
    {
        $user = Session::get('user');
        $money_arr = input('post.money_arr', []);
        $out_no_this_arr = array_column($money_arr, 'out_no_this');
        $out_no_this = array_shift($out_no_this_arr);
        $sku_out_no_arr = array_column($money_arr, 'sku_out_no');
        $count_arr = array_column($money_arr, 'count');
        $skus = Db::table('product_sku')->field('id,out_no,price,stock')->whereIn('out_no', $sku_out_no_arr)->select();
        if ($out_no_this) {
            // 修改购物车商品数量
            $count_index = array_search($out_no_this, $sku_out_no_arr);
            false === $count_index && die(json_encode(['code' => 1, 'msg' => '数据错误']));
            $count_this = $count_arr[$count_index];
            $count_this < 0 && die(json_encode(['code' => 1, 'msg' => '数量不能为负值']));
            $sku_this = $skus->filter(function($item) use($out_no_this) {
                return $item['out_no'] === $out_no_this;
            })->shift();
            $count_this > $sku_this['stock'] && die(json_encode(['code' => 1, 'msg' => '库存不足']));
            Db::table('carts')->where('uid', $user['id'])->where('sku_out_no', $out_no_this)->update(['count' => $count_this]);
        }
        exit(json_encode(['code' => 0, 'data' => $skus->toArray()]));
    }
}
